package com.cxyjy.cfyuiapi.controller;

import com.cxyjy.cfyuiapi.service.FFiveTTSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import static com.cxyjy.common.constants.CfyuiConstants.F5TTS_URL;

/**
 * @Author: JrsJony
 * @Date : 2025/1/3 17:55
 */
@Slf4j
@RestController
public class FFiveTTSController {
    @Autowired
    FFiveTTSService fFiveTTSService;

    /**
     * F5-TTS声音克隆接口
     * @param refText
     * @param genText
     * @param model
     * @param audioFile
     * @return
     */
    @PostMapping("/tts")
    public void submitTTS(@RequestParam("ref_text") String refText,
                          @RequestParam("gen_text") String genText,
                          @RequestParam("model") String model,
                          @RequestParam("audio") MultipartFile audioFile,
                          HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) {
        try {
            // 获取音频文件字节数组
            byte[] audioBytes = audioFile.getBytes();

            // 设置请求的字符编码
            httpServletRequest.setCharacterEncoding("UTF-8");

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) F5TTS_URL.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // 设置请求头，确保传输使用 UTF-8 编码
            String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.setRequestProperty("Accept-Charset", "UTF-8");

            // 输出流
            try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
                String lineEnd = "\r\n";
                String twoHyphens = "--";

                // 发送 ref_text 和 gen_text 参数
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"ref_text\"" + lineEnd + lineEnd);
                outputStream.writeBytes(new String(refText.getBytes("UTF-8"), "ISO-8859-1") + lineEnd); // 确保使用 UTF-8 编码并转换为 ISO-8859-1

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"gen_text\"" + lineEnd + lineEnd);
                outputStream.writeBytes(new String(genText.getBytes("UTF-8"), "ISO-8859-1") + lineEnd); // 确保使用 UTF-8 编码并转换为 ISO-8859-1

                // 发送 model 参数
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"model\"" + lineEnd + lineEnd);
                outputStream.writeBytes(model + lineEnd);

                // 上传音频文件
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"audio\"; filename=\"" + audioFile.getOriginalFilename() + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: " + audioFile.getContentType() + lineEnd + lineEnd);
                outputStream.write(audioBytes); // 写入文件内容
                outputStream.writeBytes(lineEnd);

                // 结束请求
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // 获取响应
                int responseCode = connection.getResponseCode();
                System.out.println("响应码: " + responseCode);

                try (BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream())) {
                    // 设置响应类型为音频
                    httpServletResponse.setContentType("audio/wav");  // 根据实际音频格式设置

                    // 将音频数据直接写入响应流
                    try (OutputStream outputStream1 = httpServletResponse.getOutputStream()) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream1.write(buffer, 0, bytesRead);
                        }
                        outputStream1.flush();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
